<template>
  <div class="app-container">
    <public-search @on-query="handleQuery" @on-reset="resetQuery">
      <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch" label-width="68px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="姓名" prop="userName">
              <el-input v-model="queryParams.userName" placeholder="请输入" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="组织机构" prop="deptName">
              <el-input v-model="queryParams.deptName" placeholder="请选择" clearable size="small"
                v-on:click.native="chooseDeptHandle" @keyup.enter.native="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="角色" prop="roleId">
              <el-select v-model="queryParams.roleId" placeholder="请选择" clearable style="width: 100%;">
                <el-option v-for="dict in roleOptions" :key="dict.roleId" :label="dict.roleName" :value="dict.roleId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </public-search>


    <public-table>
      <template slot="operate">
        <div>
          <el-button type="primary" @click="handleAdd">录入用户</el-button>
        </div>
      </template>
      <template slot="table">

        <el-table v-loading="loading" :data="userList" fit border>
          <el-table-column label="序号" align="center" width="50px" type="index" />
          <el-table-column label="姓名" align="center" key="userName" prop="userName" />
          <el-table-column label="登录名" align="center" key="nickName" prop="nickName" />
          <el-table-column label="岗位" align="center" key="nickName2" prop="nickName" />
          <el-table-column label="所属组织机构" align="center" key="deptName" prop="dept.deptName" />
          <el-table-column label="手机号" align="center" key="phonenumber" prop="phonenumber" />
          <el-table-column label="角色" align="center" key="roles" prop="roles">
            <template slot-scope="scope">
              <div v-for="(item, index) in scope.row.roles">
                {{ item.roleName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="handleUpdate(scope.row)">编辑
              </el-button>
              <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>

      <template slot="pagination">
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getList" />
      </template>
    </public-table>
    <el-dialog title="组织机构" :visible.sync="chooseDeptOpen" append-to-body width="600px">
      <choose-dept @deptValue="deptValue"></choose-dept>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="deptCancel">取 消</el-button>
        <el-button size="small" type="primary" @click="deptSubmitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUser,
  delUser,
  resetUserPwd,
  deptTreeSelect, getUser
} from '@/api/system/user'
import { getToken } from '@/utils/auth'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import ChooseProcess from '@/plugins/package/tree/chooseProcess'
import ChooseDept from '@/plugins/package/tree/chooseDept'

export default {
  name: 'User',
  dicts: ['sys_normal_disable', 'sys_user_sex'],
  components: { Treeselect, ChooseProcess, ChooseDept },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: '',
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 默认密码
      initPassword: undefined,
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      deptName: undefined,
      deptId: undefined,
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      isShowList: false,
      chooseDeptOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        roleId: undefined,
        deptName: undefined,
        deptId: undefined
      }
    }
  },
  watch: {
    // 根据名称筛选部门树

  },
  created() {
    this.getList()
    this.getDeptTree()
    getUser().then(response => {
      this.roleOptions = response.data.roles
    })
  },
  methods: {
    /**
     * 部门子页面传参到父页面
     */
    deptValue(data) {
      this.deptName = data.label
      this.deptId = data.id
    },
    /**
     * 主办部门选择-确定
     */
    deptSubmitForm() {
      this.queryParams.deptName = this.deptName
      this.queryParams.deptId = this.deptId
      this.chooseDeptOpen = false
    },
    /**
     * 主办部门选择-取消
     */
    deptCancel() {
      this.chooseDeptOpen = false
    },
    /**
     * 部门弹出
     */
    chooseDeptHandle() {
      this.chooseDeptOpen = true
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true
      listUser(this.addDateRange(this.queryParams)).then(response => {
        this.userList = response.data
        this.total = response.total
        this.loading = false
      }
      )
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.handleQuery()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.deptId = undefined
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({
        path: '/user/userInfoAdd'
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const userId = row.userId || this.ids
      this.$router.push({
        path: '/user/userInfoEdit', query: { userId: userId }
      })
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: '用户密码长度必须介于 5 和 20 之间'
      }).then(({ value }) => {
        resetUserPwd(row.userId, value).then(response => {
          this.$modal.msgSuccess('修改成功，新密码是：' + value)
        })
      }).catch(() => {
      })
    },
    /** 分配角色操作 */
    handleAuthRole: function (row) {
      const userId = row.userId
      this.$router.push('/system/user-auth/role/' + userId)
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids
      this.$modal.confirm('是否确认删除当前用户数据？').then(function () {
        return delUser(userIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '用户导入'
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
